<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="入库记录单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="entryNumber">
              <a-input v-model="model.recordNumber" placeholder="保存自动生成" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="入库类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="entryType">
              <a-select
                v-if="!formDisabled"
                v-model="model.entryType"
                placeholder="请选择入库类型"
                @change="entryTypeChange"
              >
                <a-select-option :value="11">盘盈入库</a-select-option>
                <a-select-option :value="12">手动入库</a-select-option>
              </a-select>
              <a-input v-else v-model="model.entryType_dictText"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="推送质检"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="qualityInspectionPushed"
            >
              <j-dict-select-tag
                type="list"
                v-model="model.qualityInspectionPushed"
                dictCode="yes_no"
                placeholder="请选择是否推送质检"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="入库日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="entryDate">
              <j-date placeholder="请选择入库日期" v-model="model.entryDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="handlerRemark">
              <a-input v-model="model.handlerRemark" placeholder="请输入备注"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="宝洁采购订单号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="pgPurchaseOrderNumber"
            >
              <a-input v-model="model.pgPurchaseOrderNumber" placeholder="请输入宝洁采购订单号"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="宝洁供应商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pgSupplierName">
              <a-input
                v-model="model.pgSupplierName"
                placeholder="请选择宝洁供应商"
                @click="chooseSupplier()"
                :disabled="formDisabled"
              >
              </a-input>
              <tsl-purchase-supplier
                ref="selectSuppliersList"
                :rowData="model"
                :isDisabled="formDisabled"
                @handleOk="supplierOk"
                checkval="radio"
                :supplierType="supplierType"
              ></tsl-purchase-supplier>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="宝洁供应商编号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="pgSupplierCode"
            >
              <a-input v-model="model.pgSupplierCode" placeholder="宝洁供应商编号" disabled></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <erp-all-goods-list-modal ref="materialModal" @goodRowsOk="selectMaterialConfirm" checkval="checkbox" />
    <!-- <select-material-by-category-modal ref="materialModal" @confirm="selectMaterialConfirm" /> -->
    <j-vxe-table
      keep-source
      :ref="refKeys[0]"
      :loading="inboundRecordItemTable.loading"
      :columns="inboundRecordItemTable.columns"
      :dataSource="inboundRecordItemTable.dataSource"
      :maxHeight="300"
      :disabled="formDisabled"
      :rowNumber="true"
      :rowSelection="!formDisabled"
      :toolbar="true"
      :toolbarConfig="{
        slots: ['prefix', 'suffix'],
        btn: formDisabled ? [] : ['remove', 'clearSelection'],
      }"
      @valueChange="handleItemChange"
      @remove="handleDelete"
    >
      <template #toolbarPrefix>
        <a-button @click="handleOpenMaterialModal" v-if="!formDisabled" type="primary" icon="plus"> 新增 </a-button>
      </template>
      <!-- <template v-slot:batchNumber="{ row }">
        <a-select
          v-model="row.batchNumber"
          mode="combobox"
          placeholder="请选择或输入批次号"
          :options="batchNumberOptions"
          show-search
          allow-clear
          style="width: 100%"
          :disabled="formDisabled"
        >
          <a-select-option v-for="item in batchNumberOptions" :key="item.value" :value="item.value">
            {{ item.label }}
          </a-select-option>
        </a-select>
      </template> -->
      <template v-slot:storageLocationName="{ row }">
        <a-input
          v-model="row.storageLocationName"
          placeholder="请选择储位"
          @click="chooseStorage(row)"
          :disabled="formDisabled"
        >
        </a-input>
        <storage-location
          ref="selectStorageList"
          @handleOk="storageOk"
          :warehouseCode="warehouseCode"
        ></storage-location>
      </template>
    </j-vxe-table>
    <br />
    <div class="ant-descriptions-title">作业信息</div>
    <cargo-cascader
      style="margin-bottom: 10px"
      :max-level="2"
      load-children-on-select
      v-if="!formDisabled"
      @change="cargoSelectChange" />
    <j-vxe-table
      keep-source
      ref="cargoGroupMember"
      :loading="cargoGroupMemberTable.loading"
      :columns="cargoGroupMemberTable.columns"
      :dataSource="cargoGroupMemberTable.dataSource"
      :disabled="formDisabled"
      :maxHeight="300"
      :rowNumber="true"
      :rowSelection="!formDisabled"
      :toolbar="true"
      :toolbarConfig="{
            slots: ['prefix', 'suffix'],
            btn: ['remove', 'clearSelection'],
          }"
      @remove="handleCargoDelete"
    />
    <br />
    <a-descriptions title="车辆检查项目" bordered :column="2" class="vehicle-inspection-result">
      <a-descriptions-item
        v-for="(item, index) in vehicleInspectionResult.dataSource"
        :key="index"
        :label="`${index + 1}.${item.itemName}`"
      >
        <div v-if="formDisabled">{{ item.resultValue }}</div>
        <div v-else>
          <a-select v-if="item.resultType === 1" style="width: 100%" v-model="item.resultValue">
            <a-select-option value="Y">Y</a-select-option>
            <a-select-option value="N">N</a-select-option>
            <a-select-option value="N">NA</a-select-option>
          </a-select>
          <a-input v-else-if="item.resultType === 2" v-model="item.resultValue" placeholder="请输入" />
        </div>
      </a-descriptions-item>
    </a-descriptions>
    <br />
    <div class="ant-descriptions-title">附件信息</div>
    <j-upload v-if="!formDisabled" v-model="model.filePath" :returnUrl="false" @change="handleFileChange" />
    <j-vxe-table
      v-else
      keep-source
      :ref="refKeys[2]"
      :loading="inboundRecordFileTable.loading"
      :columns="inboundRecordFileTable.columns"
      :dataSource="inboundRecordFileTable.dataSource"
      :maxHeight="300"
      :disabled="formDisabled"
      :rowNumber="true"
      :rowSelection="!formDisabled"
      :toolbar="true"
      :toolbarConfig="{
        slots: ['prefix', 'suffix'],
        btn: [],
      }"
      @valueChange="handleFileChange"
    >
      <template v-slot:action="props">
        <a @click="handlePreviewFile(props)">预览</a>
        <a-divider type="vertical" />
        <a target="_blank" rel="noopener noreferrer" :href="handleDownloadFile(props)">下载</a>
      </template>
    </j-vxe-table>
  </a-spin>
</template>

<script>
import JFormContainer from '@/components/jeecg/JFormContainer'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, validateFormModelAndTables } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { getAction, getFileAccessHttpUrl } from '@api/manage'
import JSelectGoods from '@comp/jeecgbiz/JSelectGoods.vue'
// import SelectMaterialModal from '@views/erp/base/modules/SelectMaterialModal.vue'
// import SelectMaterialByCategory from '@comp/material/SelectMaterialByCategory.vue'
// import SelectMaterialByCategoryModal from '@comp/material/modal/SelectMaterialByCategoryModal.vue'
import ErpAllGoodsListModal from '@/components/base/modal/ErpAllGoodsListModal.vue'
import utils from '@/utils/utils'
import $file from '@/libs/globalFunction/file'
import { FilePreview } from '@/utils/tslCommon'
import dayjs from 'dayjs'
import TslPurchaseSupplier from '@comp/tsl/cell/TslPurchaseSupplier.vue'
import StorageLocation from '../StorageLocation.vue'
import CargoCascader from '@comp/warehouse/CargoCascader.vue'

export default {
  name: 'InboundRecordNewForm',
  mixins: [JVxeTableModelMixin],
  components: {
    // SelectMaterialByCategoryModal,
    // SelectMaterialByCategory,
    // SelectMaterialModal,
    JSelectGoods,
    JFormContainer,
    ErpAllGoodsListModal,
    TslPurchaseSupplier,
    StorageLocation,
    CargoCascader,
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: {
        entryDate: dayjs().format('YYYY-MM-DD'),
        qualityInspectionPushed: null,
      },
      validatorRules: {
        entryType: [{ required: true, message: '请选择入库类型!' }],
        entryDate: [{ required: true, message: '请选择入库日期!' }],
        qualityInspectionPushed: [{ required: true, message: '请输入是否推送质检!' }],
      },
      url: {
        add: '/wms/inbound/inbound-record/add',
        edit: '/wms/inbound/inbound-record/edit',
        queryById: '/wms/inbound/inbound-record/queryById',
        inboundRecordItem: {
          list: '/wms/inbound/inbound-record/queryInboundRecordItemByMainId',
        },
        vehicleInspectionResult: {
          list: '/wms/inbound/inbound-record/queryVehicleInspectionResultByMainId',
        },
        vehicleInspectionItem: {
          list: '/wms/inbound/vehicle-inspection-item/list',
        },
        inboundRecordFile: {
          list: '/wms/inbound/inbound-record/queryInboundRecordFileByMainId',
        },
        outboundRecordCargoMember: {
          list: '/wms/outbound/outbound-record/queryOutboundRecordCargoMemberByMainId'
        },
      },
      confirmLoading: false,
      storageLocationOptions: [],
      batchNumberOptions: [],
      refKeys: ['inboundRecordItem', 'vehicleInspectionResult', 'inboundRecordFile'],
      // 入库单明细表
      inboundRecordItemTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '客户物料编码',
            key: 'customerMaterialCode',
            minWidth: '110px',
          },
          {
            title: '物料编码',
            key: 'materialCode',
            minWidth: '110px',
          },
          {
            title: '物料名称',
            key: 'materialName',
            minWidth: '220px',
          },
          {
            title: '规格型号',
            key: 'specificationModel',
            width: '90px',
          },
          {
            title: '单位',
            key: 'unit_dictText',
            dictCode: 'ji_unit',
            width: '60px',
            align: 'center',
          },
          {
            title: '数量',
            key: 'quantity',
            type: JVXETypes.input,
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '辅单位',
            key: 'secondaryUnit_dictText',
            dictCode: 'zl_unit',
            width: '70px',
            align: 'center',
          },
          {
            title: '辅数量',
            key: 'secondaryQuantity',
            width: '80px',
          },
          {
            title: '生产日期',
            key: 'productionDate',
            type: JVXETypes.date,
            width: '170px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '批次号',
            key: 'batchNumber',
            type: JVXETypes.input,
            placeholder: '请输入${title}',
            minWidth: '150px',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '物料批号',
            key: 'materialBatchNumber',
            type: JVXETypes.input,
            minWidth: '150px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '入库储位',
            key: 'storageLocationName',
            type: JVXETypes.slot,
            slotName: 'storageLocationName',
            minWidth: '150px',
            defaultValue: '',
          },
        ],
      },
      // 作业信息
      cargoGroupMemberTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '姓名',
            key: 'memberName',
            type: JVXETypes.normal,
            minWidth: '110px'
          },
          {
            title: '作业工种',
            key: 'jobType_dictText',
            type: JVXETypes.normal,
            minWidth: '180px'
          },
          {
            title: '作业吨数',
            key: 'jobWeight',
            type: JVXETypes.inputNumber,
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          }
        ]
      },
      // 入库车辆检查项目结果
      vehicleInspectionResult: {
        loading: false,
        dataSource: [],
      },
      // 入库记录附件表
      inboundRecordFileTable: {
        loading: false,
        columns: [
          {
            title: '附件名称',
            key: 'fileName',
            type: JVXETypes.normal,
            width: '200px',
            defaultValue: '',
          },
          {
            title: '文件大小',
            key: 'fileSizeFormat',
            type: JVXETypes.normal,
            width: '200px',
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '100px',
            align: 'center',
            slotName: 'action',
          },
        ],
        dataSource: [],
      },
      // 新增用于存储当前操作的行
      currentRow: null, 
      // 供应商类型：宝洁
      supplierType: 2,
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    warehouseCode: {
      type: String,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    if (!this.formDisabled) {
      this.model.warehouseCode = this.warehouseCode
      this.getVehicleInspectionItem()
    }
    getAction(
      `/sys/dict/getDictItems/wms_storage_location,location_name,location_code,warehouse_code='${this.warehouseCode}'`,
      {}
    ).then((res) => {
      res.result.forEach((location) => {
        location.code = location.value
        location.value = location.label
      })
      this.storageLocationOptions = res.result
    })
    const bacthdate = dayjs().format('YYYY-MM-DD')
    getAction(
      `/sys/dict/getDictItems/wms_batch_number,batch_code,batch_code,is_label_generated='0' AND status='0' AND batch_date='${bacthdate}' limit 99`,
      {}
    ).then((res) => {
      this.batchNumberOptions = res.result
    })
  },
  methods: {
    // 选择宝洁供应商
    chooseSupplier() {
      this.$nextTick(() => {
        this.$refs.selectSuppliersList.add()
      })
    },
    supplierOk({ row, data }) {
      this.$set(this.model, 'pgSupplierName', data.supplierName)
      this.$set(this.model, 'pgSupplierCode', data.supplierCode)
    },
    // 选择储位
    chooseStorage(row) {
      // 存储当前操作的行
      this.currentRow = row;  
      this.$nextTick(() => {
        this.$refs.selectStorageList.add()
      })
    },
    storageOk({ data }) {
      if (this.currentRow) {
        // 将选择的储位赋值到当前行
        this.currentRow.storageLocation = data.locationCode;
        this.currentRow.storageLocationName = data.locationName;
        // 重置当前行
        this.currentRow = null;
      }
    },
    handleOpenMaterialModal() {
      this.$refs.materialModal.showModal({ warehouseCode: this.model.warehouseCode })
    },
    addBefore() {
      this.inboundRecordItemTable.dataSource = []
      this.vehicleInspectionResult.dataSource = []
      this.inboundRecordFileTable.dataSource = []
      this.cargoGroupMemberTable.dataSource = []
    },
    selectMaterialConfirm(rows) {
      if (!rows || rows.length <= 0) {
        return
      }
      const inboundRecordItemList = rows.map((item, index) => {
        return {
          uid: index,
          customerMaterialCode: item.customCode,
          customerName: item.customerName,
          brand: item.brand,
          shelfLife: item.qualityDays,
          materialCode: item.code,
          materialName: item.name,
          materialDesc: item.categoryDescription,
          specificationModel: item.noneSpec,
          materialCategory: item.categoryNo,
          materialClassify: item.classify,
          productionDate: null,
          unit: item.meUnit,
          unit_dictText: item.meUnit_dictText,
          quantity: null,
          secondaryUnit: item.auUnit,
          secondaryUnit_dictText: item.auUnit_dictText,
          secondaryQuantity: null,
          unitConversionRate: item.coRate,
          batchNumber: null,
          materialBatchNumber: null,
          storageLocation: null,
          storageLocationName: null,
        }
      })
      this.inboundRecordItemTable.dataSource.push(...inboundRecordItemList)
    },
    handleItemChange({ value, col, rowIndex }) {
      if (col.field === 'quantity' && value) {
        const item = this.inboundRecordItemTable.dataSource[rowIndex]
        item.secondaryQuantity = utils.mul(value, item.unitConversionRate)
      }
    },
    handleDelete({ deleteRows }) {
      this.inboundRecordItemTable.dataSource = this.inboundRecordItemTable.dataSource.filter(
        (row) => !deleteRows.some((item) => item.id === row.id)
      )
    },
    handleFileChange(fileList) {
      if (!fileList || fileList.length <= 0) {
        return
      }
      fileList.forEach((item) => {
        item.fileSizeFormat = $file.calculateFileSize(item.fileSize)
      })
      this.inboundRecordFileTable.dataSource = fileList
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {})
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.inboundRecordItem.list, params, this.inboundRecordItemTable, (res) => {
          if (this.inboundRecordItemTable.dataSource && this.inboundRecordItemTable.dataSource.length > 0) {
            this.inboundRecordItemTable.dataSource.forEach((item) => {
              this.$set(item, 'storageLocationName', item.storageLocation_dictText)
            })
          }
        })
        this.requestSubTableData(this.url.vehicleInspectionResult.list, params, this.vehicleInspectionResult)
        this.requestSubTableData(this.url.inboundRecordFile.list, params, this.inboundRecordFileTable, (res) => {
          if (this.inboundRecordFileTable.dataSource && this.inboundRecordFileTable.dataSource.length > 0) {
            this.inboundRecordFileTable.dataSource.forEach((item) => {
              this.$set(item, 'fileSizeFormat', $file.calculateFileSize(item.fileSize))
            })
          }
        })
        this.requestSubTableData(this.url.outboundRecordCargoMember.list, params, this.cargoGroupMemberTable)
      }
    },
    getAllTable() {
      let values = ['inboundRecordItem'].map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    handleOk() {
      this.getAllTable()
        .then((tables) => {
          return validateFormModelAndTables(this.$refs.form, this.model, tables)
        })
        .then((allValues) => {
          const dataSource = this.inboundRecordItemTable.dataSource
          if (!dataSource || dataSource.length <= 0) {
            this.validateError('请选择物料')
            reject()
          }
          if (dataSource && dataSource.length > 0) {
            const batchNumbers = dataSource.map((item) => item.batchNumber)
            const uniqueBatchNumbers = new Set(batchNumbers)
            if (batchNumbers.length !== uniqueBatchNumbers.size) {
              this.validateError('批次号不能重复')
              reject()
            }
          }
          return this.validateSubForm(allValues)
        })
        .then(() => {
          let formData = this.classifyIntoFormData()
          // 发起请求
          return this.request(formData)
        })
    },
    /** 整理成formData */
    classifyIntoFormData() {
      let main = Object.assign(this.model, {})
      return {
        ...main,
        inboundRecordItemList: this.inboundRecordItemTable.dataSource.map((item) => {
          let matched = (this.storageLocationOptions || []).find((opt) => opt.value === item.storageLocation)
          return {
            ...item,
            id: null,
            storageLocation: matched ? matched.code : item.storageLocation,
          }
        }),
        vehicleInspectionResultList: this.vehicleInspectionResult.dataSource.filter((item) => item.resultValue),
        inboundRecordFileList: this.inboundRecordFileTable.dataSource.map((item) => {
          return {
            ...item,
            id: null,
          }
        }),
        outboundRecordCargoMemberList: this.cargoGroupMemberTable.dataSource.map(item => {
          return {
            ...item,
            cargoType: 1,
            id: null
          }
        }),
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    handlePreviewFile({ row }) {
      FilePreview(row.filePath)
    },
    handleDownloadFile({ row }) {
      return row.filePath
    },
    entryTypeChange(val) {
      const falseValue = [5, 6, 7, 8, 11, 12]
      const trueValue = [1, 2, 3, 4, 9, 10, 13, 14, 15, 16]
      if (falseValue.includes(val)) {
        this.model.qualityInspectionPushed = 0
      } else if (trueValue.includes(val)) {
        this.model.qualityInspectionPushed = 1
      }
    },
    getVehicleInspectionItem() {
      getAction(this.url.vehicleInspectionItem.list).then((res) => {
        let { result } = res
        if (result && result.records) {
          this.vehicleInspectionResult.dataSource = result.records.map((item) => {
            return {
              itemName: item.itemName,
              resultType: item.resultType,
              inspectionItemId: item.id,
              resultValue: item.resultType === 1 ? 'Y' : null,
            }
          })
        }
      })
    },
    cargoSelectChange({ value, list }) {
      if (list.length > 0) {
        this.cargoGroupMemberTable.dataSource = list.map(item => {
          return {
            memberName: item.memberName,
            jobType: item.jobType,
            jobType_dictText: item.jobType_dictText,
            memberId: item.id,
            groupId: item.groupId,
            teamId: value[0]
          }
        })
      }
    },
    handleCargoDelete({ deleteRows }) {
      this.cargoGroupMemberTable.dataSource = this.cargoGroupMemberTable.dataSource.filter(row =>
        !deleteRows.some(item => item.id === row.id)
      )
    },
  },
}
</script>

<style scoped lang="less">
.vehicle-inspection-result {
  ::v-deep {
    .ant-descriptions-item-content {
      padding: 0 24px;
    }
  }
}
</style>
